package top.royaltownserver;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.royaltownserver.util.ConfigLoader;

import java.io.File;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class daemonProcess {

    // 阿里云短信服务配置
    static String product;
    static String domain;
    static String accessKeyId;
    static String accessKeySecret;
    static String signName;
    static String templateCode;
    static String[] phoneNumbers;
    static String timeMode;
    static String phoneNumbersStr;
    static String filePath;
    static IClientProfile profile;
    static IAcsClient acsClient;
    static int checkInterval;
    static boolean enableSmsNotification;
    private static final Logger logger = LoggerFactory.getLogger(daemonProcess.class);

    public static void main(String[] args) {
        logger.info("服务器守护已启动");
        logger.info("准备加载配置文件");
        try {
            Properties props = ConfigLoader.loadConfig();
            String enableSmsStr = props.getProperty("enableSmsNotification", "true");
            enableSmsNotification = Boolean.parseBoolean(enableSmsStr);
            if (enableSmsNotification) {
                product = props.getProperty("sms.product");
                domain = props.getProperty("sms.domain");
                accessKeyId = props.getProperty("sms.accessKeyId");
                accessKeySecret = props.getProperty("sms.accessKeySecret");
                signName = props.getProperty("sms.signName");
                templateCode = props.getProperty("sms.templateCode");
                phoneNumbersStr = props.getProperty("sms.phoneNumbers");
                phoneNumbers = phoneNumbersStr.split(",");
                logger.info("阿里云短信服务配置已加载");
            }
            else {
                logger.info("🔕 短信通知已关闭，跳过加载阿里云短信服务配置");
            }
            checkInterval = Integer.parseInt(props.getProperty("checkInterval"));
            timeMode = props.getProperty("timeMode");
            filePath = props.getProperty("filePath");

            // 后续初始化短信客户端等逻辑...
            logger.info("✅ 配置加载完成，当前配置：");
            if (enableSmsNotification){
                logger.info("product: " + product);
                logger.info("domain: " + domain);
                logger.info("accessKeyId: " + accessKeyId);
                logger.info("签名: " + signName);
                logger.info("模板编码: " + templateCode);
                logger.info("发送手机: " + String.join(",", phoneNumbers));
            }
            logger.info("时间模式: " + timeMode);
            logger.info("检查时间间隔: " + checkInterval);
            logger.info("设定的重启脚本路径(服务器启动bat): " + filePath);

        } catch (Exception e) {
            logger.error("加载配置失败: " + e);
            e.printStackTrace();
            System.exit(1);
        }
        if (enableSmsNotification){
        // 设置超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        // 初始化短信客户端
        try {
            profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou","Dysmsapi", domain); // 如果仍然需要
            acsClient = new DefaultAcsClient(profile);
        } catch (ClientException e) {
            e.printStackTrace();
        }

        }

        // 每5分钟检查一次 bedrock_server_mod.exe 是否存在
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        TimeUnit unit;
        switch (timeMode.toLowerCase()) {
            case "minute":
                unit = TimeUnit.MINUTES;
                break;
            case "hour":
                unit = TimeUnit.HOURS;
                break;
            case "second":
                unit = TimeUnit.SECONDS;
                break;
            default:
                unit = TimeUnit.DAYS;
                break;
        }
        scheduler.scheduleAtFixedRate(() -> checkProcessAndSendSms(acsClient), 0,checkInterval, unit);
    }
    private static void checkProcessAndSendSms(IAcsClient acsClient) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "tasklist");
            Process process = processBuilder.start();

            java.util.Scanner scanner = new java.util.Scanner(process.getInputStream(),"GBK");
            boolean found = false;

            while (scanner.hasNextLine()) {
                if (scanner.nextLine().contains("bedrock_server_mod.exe")) {
                    found = true;
                    break;
                }
            }
            scanner.close();

            if (!found) {
                logger.info("⚠️ bedrock_server_mod.exe 未运行，正在尝试启动...");

                boolean started = false;
                int retryCount = 0;
                int maxRetries = 3;

                while (!started && retryCount < maxRetries) {
                    retryCount++;
                    logger.info("🔄 正在尝试启动服务（第 " + retryCount + "/" + maxRetries + " 次）...");

                    try {
                        // ✅ 新增：打开一个 CMD 窗口运行服务
                        ProcessBuilder startBuilder = new ProcessBuilder(
                                "cmd.exe", "/c", "start", "cmd", "/k", "bedrock_server_mod.exe"
                        );
                        startBuilder.directory(new File(filePath)); // 设置工作目录
                        Process startProcess = startBuilder.start();

                        Thread.sleep(10000); // 等待10秒再检查是否成功启动

                        // 再次检查进程是否存在
                        Process checkProcess = Runtime.getRuntime().exec("tasklist");
                        Scanner checkScanner = new Scanner(checkProcess.getInputStream());
                        while (checkScanner.hasNextLine()) {
                            if (checkScanner.nextLine().contains("bedrock_server_mod.exe")) {
                                started = true;
                                logger.info("✅ 进程已成功启动！");
                                break;
                            }
                        }
                        checkScanner.close();

                    } catch (Exception e) {
                        logger.error("❌ 启动失败：" + e.getMessage());
                        Thread.sleep(10000); // 等待10秒后再次尝试
                    }
                }

                if (!started && enableSmsNotification) {
                    logger.info("❌ 已尝试多次仍未启动成功，准备发送短信...");

                    // ✅ 发送短信通知
                    for (String number : phoneNumbers) {
                        try {
                            SendSmsRequest request = new SendSmsRequest();
                            request.setPhoneNumbers(number); // 每次设置不同的手机号
                            request.setSignName(signName);
                            request.setTemplateCode(templateCode);
                            request.setTemplateParam("{\"code\":\"5000\"}");

                            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
                            if ("OK".equals(sendSmsResponse.getCode())) {
                                logger.info("📲 短信已发送给：" + number);
                            } else {
                                logger.info("❌ 短信发送失败给：" + number + "，原因：" + sendSmsResponse.getMessage());
                            }
                        } catch (Exception e) {
                            logger.error("❌ 向 " + number + " 发送短信时出错：" + e.getMessage());
                        }
                    }
                }else if (!started) {
                    logger.info("🔕 短信通知已禁用，不会发送短信");
                }
            } else {
                logger.info("✅ bedrock_server_mod.exe 正常运行中");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

